package com.ldzhao.blog.util;

import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;

import java.lang.reflect.Method;

/**
 * <ClassName>GEOSearcher</ClassName>
 * <Description>地理位置查询</Description>
 *
 * @author liuxianzhao
 * @date 2018/8/4 13:51
 */
@Slf4j
public class GEOSearcher {
    private static final String MEMORY_ALGORITHM = "memorySearch";
    private static Method searchMethod = null;
    private static DbSearcher searcher = null;
    private static final String IP2REGION_PATH = "/app/server/zblog/ip2region.db";

    static {
        log.info("init GEOSearcher .....");
        try {
            DbConfig config = new DbConfig();
            searcher = new DbSearcher(config, IP2REGION_PATH);
            searchMethod = searcher.getClass().getMethod(MEMORY_ALGORITHM, String.class);
        } catch (Exception e) {
            log.error("init GEOSearcher error", e);
        }
    }

    public static DataBlock search(String ip) {
        try {
            return (DataBlock) searchMethod.invoke(searcher, ip);
        } catch (Exception e) {
            log.error("查询IP地址失败......", e);
        }
        return null;
    }

    public static void main(String[] args) {
        DataBlock search = search("54.36.148.234");
        log.info(search.toString());
    }
}
